from pygame.draw import aaline
from math import sin, cos

class Drawer:
	def __init__(self, screen, ORIGINX, ORIGINY):
		self.screen = screen
		self.ORIGINX = ORIGINX
		self.ORIGINY = ORIGINY

	def draw_3dline(self, surface, color, a, b, width=2):
		"""Convert 3D coordinates to 2D and draw line."""
		ax, ay = a[0]+(a[2]*0.3)+self.ORIGINX, a[1]+(a[2]*0.3)+self.ORIGINY
		bx, by = b[0]+(b[2]*0.3)+self.ORIGINX, b[1]+(b[2]*0.3)+self.ORIGINY
		aaline(surface, color, (ax, ay), (bx, by), width)

	def draw_cube(self, surface, color, cube):
		"""Draw 3D cube."""
		a, b, c, d, e, f, g, h = cube

		self.draw_3dline(surface, color, a, b)
		self.draw_3dline(surface, color, b, c)
		self.draw_3dline(surface, color, c, d)
		self.draw_3dline(surface, color, d, a)

		self.draw_3dline(surface, color, e, f)
		self.draw_3dline(surface, color, f, g)
		self.draw_3dline(surface, color, g, h)
		self.draw_3dline(surface, color, h, e)

		self.draw_3dline(surface, color, a, e)
		self.draw_3dline(surface, color, b, f)
		self.draw_3dline(surface, color, c, g)
		self.draw_3dline(surface, color, d, h)

	def draw_cube_lines(self, surface, color, p0, p1):
		"""Draw lines of cube."""
		for point in range(len(p0)):
			self.draw_3dline(surface, color, p0[point], p1[point])

	def draw_square(self, surface, color, square):
		for vetor in square:
			self.draw_3dline(surface, color, vetor[0], vetor[1])


class Rotator:
	def rotate_3dpoint(self, p, angle, axis):
		"""Rotate a 3D point around given axis."""
		ret = [0, 0, 0]
		cosang = cos(angle)
		sinang = sin(angle)
		ret[0] += (cosang+(1-cosang)*axis[0]*axis[0])*p[0]
		ret[0] += ((1-cosang)*axis[0]*axis[1]-axis[2]*sinang)*p[1]
		ret[0] += ((1-cosang)*axis[0]*axis[2]+axis[1]*sinang)*p[2]
		ret[1] += ((1-cosang)*axis[0]*axis[1]+axis[2]*sinang)*p[0]
		ret[1] += (cosang+(1-cosang)*axis[1]*axis[1])*p[1]
		ret[1] += ((1-cosang)*axis[1]*axis[2]-axis[0]*sinang)*p[2]
		ret[2] += ((1-cosang)*axis[0]*axis[2]-axis[1]*sinang)*p[0]
		ret[2] += ((1-cosang)*axis[1]*axis[2]+axis[0]*sinang)*p[1]
		ret[2] += (cosang+(1-cosang)*axis[2]*axis[2])*p[2]
		return ret

	def rotate_object(self, obj, angle, axis):
		"""Rotate an object around given axis."""
		for i in range(len(obj)):
			obj[i] = self.rotate_3dpoint(obj[i], angle, axis)

	def rotate_cube(self, cube, points_of_cube, direction):
		if direction == "R": eixo = (0, 1, 0)
		elif direction == "L": eixo = (0, -1, 0)
		elif direction == "D": eixo = (-1, 0, 0)
		elif direction == "U": eixo = (1, 0, 0)

		self.rotate_object(cube, 0.1, eixo)
		for point in points_of_cube:
			self.rotate_object(point, 0.1, eixo)

